<template>
	<template v-if="isAlready">
	<draggable v-if="drag" class=" tableDragAreaClass" v-model="widget.props.columns" animation="300"
			   :style="'height:'+ dragAreaHeight+'px;'"
			   item-key="id" :group="{name:'columns'}"
			   @change="dragChange(widget.props.columns)">
		<template #item="{ element }">
			<div class="tableItemClass" @click="dblClick(element)">
				{{ element.label||element.name }}
			</div>
		</template>
	</draggable>
	<div style="width: 100%;">
		<div v-if="!drag" style="float: left;width: 100%; margin-bottom: 0px;margin-top: 3px;">
			<div style="float: right;margin-top: -37px;margin-right: 20px;">
				<el-button v-if="model._editFlag" link plain type="primary" @click="btnClick('addAsset')" :loading="loading">添加明细</el-button>
				<el-button v-if="model._editFlag||model._editAssets" link plain type="warning" @click="btnClick('editAssets')" :loading="loading">批量编辑</el-button>
				<el-button v-if="model._editFlag" link plain type="danger"   @click="del" :loading="loading">批量移除</el-button>
				<el-button v-if="model._editFlag&&model._importAssets!==false" link plain type="primary" @click="btnClick('importAssets')" :loading="loading">导入明细</el-button>
				<el-button v-if="model.documentType==='in'" link plain type="primary" @click="btnClick('labelPrint')" :loading="loading">标签打印</el-button>
				<el-button v-if="model._editFlag && model.documentType==='in'" link plain type="primary" @click="btnClick('importImage')" :loading="loading">导入图片</el-button>
<!--				<el-button link plain type="info" @click="exp" :loading="loading">导出</el-button>-->
			</div>
		</div>
		<div style="float: left;width: 100%;margin-top: -6px;" class="document-detail-table">
			<ex-table :id="'documentDetailTable'+widget.id" ref="table" :minHeight="210" :min-row="5" :maxHeight="360" :tabletype="'detail'" :columns="widget.props.columns" :url="apiUrl" size="small"
					  :drag="drag" :params="{documentId:model.id}" @columnClick="columnClickHandler" :warning-row="model._warningRow"></ex-table>
		</div>
	</div>

    <div v-if="drag" class="innerDrawer">
      <el-drawer v-model="drawerModel" size="130px;" direction="btt" :withHeader="false"
                 style="position: absolute;z-index: -1;">
        <el-form label-width="100" label-position="right" style="padding: 10px 10px 0 10px;">
          <el-row>
            <el-col :span="6" class="colClass">
              <el-form-item label="属性名称">
                {{ currentColumn.name }}  - {{currentColumn.code}}
              </el-form-item>
            </el-col>
            <el-col :span="6" class="colClass">
              <el-form-item label="显示名称">
                <el-input size="small" v-model="currentColumn.label"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="6" class="colClass">
              <el-form-item label="存储字段">
                <el-input size="small" v-model="currentColumn.nodeName" placeholder="存储在数据表中的字段编码(驼峰命名规则)"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6" class="colClass">
              <el-form-item label="占用宽度">
                <el-input-number size="small" v-model="currentColumn.width" :min="30"
                                 :max="1000"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="6" class="colClass">
              <el-form-item label="对齐方式">
                <el-input size="small" v-model="currentColumn.align"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6" class="colClass">
              <el-form-item label="支持排序">
                <el-switch
                    v-model="currentColumn.sortable"
                    style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                    :active-value="true"
                    :inactive-value="false">
                </el-switch>
              </el-form-item>
            </el-col>
            <el-col :span="6" class="colClass">
              <el-form-item label="点击事件">
                <el-input size="small" v-model="currentColumn.click"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6" class="colClass">
              <el-form-item label="固定值">
                <el-input size="small" v-model="currentColumn.fixedValue"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6" class="colClass">
              <el-form-item label="统计值">
                <el-switch
                    v-model="currentColumn.summary"
                    style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                    :active-value="true"
                    :inactive-value="false">
                </el-switch>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-drawer>
    </div>
  </template>
</template>
<script>

import draggable from "vuedraggable";
import ExFormItem from "@/components/exFormItem/index.vue";
import ExTable from "@/components/exTable/index.vue";
import formRule from "@/utils/formRule";
import globalparam from "@/constant/model/globalparam";



export default {
  name: "dyTable",
  components: {ExTable, ExFormItem, draggable},
  props: {
    model: {type: Object, default: {}},
    widget: {type: Object, default: null},
    drag: {type: Boolean, default: false},
  },
  data() {
    return {
      isAlready: false,
      loading:false,
      dragAreaHeight: 40,
      drawerModel: false,
      currentColumn: null,
      apiUrl: null,
      buttonAreaVisible: false,
      showCard:false,
      entity: {},
      click: this.$store.state.click,
    }
  },
  watch: {
    click: {
      handler(val) {
        let clickState = val[this.model.id]
        if(clickState){
          // if(clickState.clear){
          // 	this.$store.dispatch("removeClick", this.model.id);
          // }
          if(clickState.refresh){
            this.$store.dispatch("removeClick", this.model.id);
            this.searchHandler();
          }
        }
      },
      deep: true,
      immediate: false,
    }
  },
  async created() {

    if (!this.widget.props.columns) {
      this.widget.props.columns = [];
    }

    if (!this.drag) {
      if (this.model._btnAuth) {
        this.model._warningRow = false;
        if (this.model._btnAuth.editAsset) {
          this.model._warningRow = true;
        }
        if (this.model._btnAuth.editAssets) {
          this.model._warningRow = true;
          this.model._editAssets = true;
        }
      } else {
        this.model._warningRow = true;
      }

      for (const column of this.widget.props.columns) {
        let oriColumn = await this.$cache.data.loadColumn(column.columnId);
        Object.assign(column,oriColumn);
        if (column.click) {
          if (this.model._btnAuth) {
            let btns = column.click.split(",");
            let count = 0;
            let permissions = "";
            btns.forEach(btn => {
              if (this.model._btnAuth[btn]) {
                permissions = permissions + btn+ ",";
                count++;
              }
            });
            column.permissions = permissions.substring(0,permissions.length-1);
            column.buttonAreaVisible = count !== 0;

          }
          if(column.fixedValue){
            let fixeds = column.fixedValue.split(",");
            if(fixeds.length>1){
              column.width=(fixeds.length*45).toString();
            }
          }
        }
        formRule.updateColumnFormatter(column);

      }

      this.apiUrl = this.$API.asset.documentDetail.page.url;
      if (!this.model.id) {
        this.apiUrl = null;
      }

      //查询是否支持导入功能
      let minioServerUrl = await this.$TOOL.minioServerUrl();
      let paramValue = await this.$cache.data.loadGlobalParam(globalparam.documentDetailImportTemplate.paramCode);
      let templateUrl = null;
      if (paramValue&&paramValue[this.model.documentConfigId]) {
        let tempFiles = this.$TOOL.toObj(paramValue[this.model.documentConfigId]);
        if (tempFiles[0]) {
          templateUrl = minioServerUrl + tempFiles[0].realUrl;
        }
      }
      if(!templateUrl){
        this.model._importAssets=false;
      }

      if(this.model&&this.model.processType&&(this.model.processType.code==="OARK"||this.model.processType.code==="HTRK"||this.model.processType.code==="CJRK")){
        this.model._importAssets = false;
      }
    }

    // if(!this.model.name){
    // 	this.model._editFlag = false;
    // }

    this.isAlready = true;
  },

  methods: {
    //点击其中一个字段时，将当前选中字段替换成点击的字段
    dblClick: function (column) {
      this.currentColumn = column;
      this.drawerModel = true;
    },

    dragChange: function (columns) {
      columns.forEach((item, index) => {
        item.orderWeight = index;
      })
      this.$refs.table.ctrlColumns = columns;
    },
    async searchHandler() {
      let queryParams = {documentId: this.model.id};
      await this.$refs.table.refresh(queryParams);
    },
    columnClickHandler(name,data){
      this.btnClick(name,data);
    },
    //添加
    async btnClick(name, row) {
      let data = {};
      if (name === 'deleteAsset') {
        this.del(this, row);
        return;
      }
      if (name === 'addAsset') {
        data = {documentId: this.model.id};
      }
      if (name === 'editAsset') {
        if (!row) {
          row = this.$refs.table.selectionOne();
        }
        if (!row) {
          return;
        }
        data = row;
      }
      if (name === 'editAssets') {
        let records = this.$refs.table.dataRecords();
        if (records.length === 0) {
          this.$message.warning("没有可以编辑的数据");
          return;
        }
        let selections = this.$refs.table.selections();
        if (selections.length === 0) {
          let confirm = await this.$confirm('当前未选中单据明细,批量编辑后会将单据中所有明细更新为一样的信息，请确认是否继续操作？', '提示', {type: 'warning'}).then(() => {
            return true;
          }).catch(() => {
            return false;
          });
          if(!confirm) return ;
          // selections = await this.getAllRecords();
          data = {type:"all",selections:records};
        }else{
          let confirm = await this.$confirm('当前选中'+selections.length+'条单据明细,批量编辑后会将选中的明细更新为一样的信息，请确认是否继续操作？', '提示', {type: 'warning'}).then(() => {
            return true;
          }).catch(() => {
            return false;
          });
          if(!confirm) return ;
          data = {type:"select",selections:selections};
        }
      }
      if (name === 'labelPrint') {
        let records = this.$refs.table.dataRecords();
        if (records.length === 0) {
          this.$message.warning("没有可以操作的明细数据");
          return;
        }
        let selections = this.$refs.table.selections();
        if (selections.length === 0) {
          let confirm = await this.$confirm('是否打印全部资产明细的标签', '提示', {type: 'warning'}).then(() => {
            return true;
          }).catch(() => {
            return false;
          });
          if(!confirm) return ;
          selections = await this.getAllRecords();
          data = {selections:selections};
        }else{
          data = {selections:selections};
        }
      }
      if (name === 'importAssets') {
        data = {};
      }
      if (name === 'showAsset') {
        if (!row) {
          row = this.$refs.table.selectionOne();
        }
        if (!row) {
          return;
        }
        data = row;
      }


      this.$store.dispatch("addClick", {id: this.model.id, method: name, data: data});

    },
    async getAllRecords() {
      let res = await this.$API.asset.documentDetail.list.post({documentId: this.model.id});
      if (res.code === 2000){
        return res.data;
      }
      return [];
    },
    //批量删除
    async del(_this,row) {
        _this = this;
      let records = _this.$refs.table.dataRecords();
      if (records.length === 0) {
        this.$message.warning("没有可以删除的数据");
        return;
      }
		let documentConfig = await _this.$cache.data.loadDocumentConfig(_this.model.documentConfigId);
		if(documentConfig.type!=='permission'&&documentConfig.type!=='in'){
			_this.$message.warning("提示：若操作的资产包含配件或为配件且已绑定，那么相关联的资产将会同步移除，请知晓!");
		}

      let selections = [];
      if(row){
        selections.push(row);
      }else{
        selections = _this.$refs.table.selections();
      }
      if (selections.length === 0) {
        let confirm = await _this.$confirm('是否删除单据的所有资产明细', '提示', {type: 'warning'}).then(async () => {
          _this.loading = true;
          selections= await _this.getAllRecords();
          var delarray = [];
          for (let index = 0; index < selections.length; index++) {
            const element = selections[index];
            delarray.push(element.id);
          }
          var res = await _this.$API.asset.documentDetail.deleteByIds.post(delarray);
          if (res.code === 2000) {
            _this.$message.success(_this.$t("code."+res.code));
            await _this.searchHandler();
            _this.$store.dispatch("commit",selections[0].entityName);
          }
          _this.loading = false;
        }).catch(() => {

        });
        if(!confirm) return ;
      }else{
        _this.$confirm(`确定删除选中的 ${selections.length} 项吗？`, '提示', {
          type: 'warning'
        }).then(async () => {
          _this.loading = true;
          var delarray = [];
          for (let index = 0; index < selections.length; index++) {
            const element = selections[index];
            delarray.push(element.id);
          }
          var res = await _this.$API.asset.documentDetail.deleteByIds.post(delarray);
          if (res.code === 2000) {
            _this.$message.success(_this.$t("code."+res.code));
            await _this.searchHandler();
            _this.$store.dispatch("commit",selections[0].entityName);
          }
          _this.loading = false;
        }).catch(() => {
          _this.loading = false;
        });
      }
    },
    //导出
    async exp(_this,index) {
      let confirm = await this.$confirm('请确认是否执行此操作', '提示', {type: 'warning'}).then(() => {return true;}).catch(() => {return false;});
      if (!confirm) return;
      _this = this;
      _this.loading = true;
      let queryPrams = _this.$refs.table.queryParams();
      let res = await _this.$API.asset.documentDetail.export.post(queryPrams);
      if (res.code === 2000) {
        await _this.$alert(_this.$t('common.export_request_success'), "提示", {type: 'success'}).catch(()=>{});
      }
      _this.loading = false;
    },

  }
}
</script>
<style>
.tableItemClass {
  cursor: move;
  float: left;
  background: #fff;
  height: 35px;
  text-align: center;
  horiz-align: center;
  border: 1px dashed #e6e6e6;
}

.tableItemClass:hover {
  border-color: rgb(71, 231, 250);
}

.tableDragAreaClass {
  height: 40px;
  background: rgba(243, 149, 95, 0.1);
}
</style>
<script setup>
</script>
